package com.gszyxy.mallfour.consumer.handler;

import com.gszyxy.mallfour.consumer.params.ConsumerRequestParams;
import com.gszyxy.mallfour.consumer.pojo.Consumer;
import com.gszyxy.mallfour.consumer.service.ConsumerService;
import com.gszyxy.mallfour.merchant.pojo.Goods;
import com.gszyxy.mallfour.merchant.service.MerchantService;
import com.gszyxy.mallfour.utils.MD5;
import com.gszyxy.mallfour.utils.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("consumer")
public class ConsumerHandler {


    @Resource
    private ConsumerService consumerService;

    //注入商家的service
    @Resource
    private MerchantService merchantService;

    @RequestMapping("add")
    public R register(@RequestBody ConsumerRequestParams consumer) {
        Consumer consumer_obj = consumerService.findByAccount(consumer.getAccount());

        if (consumer_obj != null) {
            return R.fail("账号已经被注册");
        }
        consumer.setPasswd(MD5.getMD5Hash(consumer.getPasswd()));
        return consumerService.register(consumer) > 0 ? R.ok("注册成功") : R.fail("注册失败");
    }
    @PostMapping("login")
    public R login(@RequestBody ConsumerRequestParams consumer, HttpServletRequest request) {
        consumer.setPasswd(MD5.getMD5Hash(consumer.getPasswd()));
        Consumer consumer_obj = consumerService.login(consumer);
        if (consumer_obj != null) {
            request.getSession().setAttribute("account", consumer.getAccount());
        }
        return consumer_obj != null ? R.ok("登录成功") : R.fail("账号或密码错误");
    }

    @GetMapping("findAll")
    public R findAll() {
        List<Goods> allGoods = merchantService.findAllGoods();
        return allGoods.size() > 0 ? R.ok(allGoods) : R.fail("没有商品");
    }
}
